<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="访客姓名" prop="visitorName">
        <el-input
          v-model="queryParams.visitorName"
          placeholder="请输入访客姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="老人姓名" prop="elderUserId">
        <el-select
          v-model="queryParams.elderUserId"
          placeholder="请选择老人"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option
            v-for="item in elderOptions"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option label="待审核" value="0" />
          <el-option label="已通过" value="1" />
          <el-option label="已拒绝" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:visitor:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="visitorList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="访客姓名" align="center" prop="visitorName" />
      <el-table-column label="联系电话" align="center" prop="visitorPhone" />
      <el-table-column label="身份证号" align="center" prop="visitorIdCard" />
      <el-table-column label="老人姓名" align="center" prop="elderName" />
      <el-table-column
        label="来访时间"
        align="center"
        prop="visitTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.visitTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="离开时间"
        align="center"
        prop="leaveTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.leaveTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="来访事由" align="center" prop="visitReason" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.visitor" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status === '0'"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status === '0'"
            v-hasPermi="['system:visitor:delete']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleAudit(scope.row)"
            v-show="scope.row.status === '0'"
            v-hasPermi="['system:visitor:audit']"
            >审核</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleAudit(scope.row)"
            v-if="scope.row.status === '1'"
            >离开</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改来客访记对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      @open="handleOpen"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="老人" prop="elderUserId">
          <el-select
            v-model="form.elderUserId"
            placeholder="请选择老人"
            filterable
            @change="handleElderChange"
          >
            <el-option
              v-for="item in elderOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="访客姓名" prop="visitorId">
          <el-select
            v-model="form.visitorId"
            placeholder="请选择访客"
            filterable
            :disabled="!form.elderUserId"
          >
            <el-option
              v-for="item in familyOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="visitorPhone">
          <el-input v-model="form.visitorPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="身份证号" prop="visitorIdCard">
          <el-input v-model="form.visitorIdCard" placeholder="请输入身份证号" />
        </el-form-item>

        <el-form-item label="来访时间" prop="visitTime">
          <el-date-picker
            v-model="form.visitTime"
            type="datetime"
            placeholder="选择来访时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <!-- <el-form-item label="离开时间" prop="leaveTime">
          <el-date-picker
            v-model="form.leaveTime"
            type="datetime"
            placeholder="选择离开时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item> -->
        <el-form-item label="来访事由" prop="visitReason">
          <el-input
            v-model="form.visitReason"
            type="textarea"
            placeholder="请输入来访事由"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      :title="'审核来客访记'"
      :visible.sync="auditOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="auditForm"
        :model="auditForm"
        :rules="auditRules"
        label-width="80px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAudit">确 定</el-button>
        <el-button @click="cancelAudit">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listVisitor,
  getVisitor,
  delVisitor,
  addVisitor,
  updateVisitor,
  exportVisitor,
} from "@/api/system/visitor";
import { listElder as listUser } from "@/api/system/user";
import { getFamiliesByElder } from "@/api/system/relation";

export default {
  name: "Visitor",
  dicts: ["visitor"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 来客访记表格数据
      visitorList: [],
      // 老人选项
      elderOptions: [],
      // 家属选项
      familyOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        visitorName: null,
        elderUserId: null,
        status: null,
      },
      // 表单参数
      form: {
        id: null,
        visitorName: null,
        visitorPhone: null,
        visitorIdCard: null,
        elderUserId: null,
        elderName: null,
        visitTime: null,
        leaveTime: null,
        visitReason: null,
        status: "0",
      },
      // 表单校验
      rules: {
        visitorId: [
          { required: true, message: "访客姓名不能为空", trigger: "blur" },
        ],
        visitorPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        visitorIdCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: "请输入正确的身份证号码",
            trigger: "blur",
          },
        ],
        elderUserId: [
          { required: true, message: "请选择老人", trigger: "change" },
        ],
        visitTime: [
          { required: true, message: "请选择来访时间", trigger: "change" },
        ],
        visitReason: [
          { required: true, message: "来访事由不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" },
        ],
      },
      // 审核对话框
      auditOpen: false,
      // 审核表单
      auditForm: {
        id: null,
        status: "1",
        auditRemark: null,
      },
      // 审核表单校验
      auditRules: {
        status: [
          { required: true, message: "请选择审核结果", trigger: "change" },
        ],
        auditRemark: [
          { required: true, message: "请输入审核意见", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getList();
    this.getElderList();
  },
  activated() {
    this.getList();
    this.getElderList();
  },
  methods: {
    handleOpen() {
      this.getElderList();
    },
    /** 查询来客访记列表 */
    getList() {
      this.loading = true;
      listVisitor(this.queryParams).then((response) => {
        this.visitorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取老人列表 */
    getElderList() {
      listUser({ roleKey: "elder", status: "0" }).then((response) => {
        // 过滤出老人角色的用户
        this.elderOptions = response.rows;
      });
    },
    /** 获取家属列表 */
    getFamilyList(elderUserId) {
      getFamiliesByElder(elderUserId).then((response) => {
        // 从关联记录中提取家属用户信息
        this.familyOptions = response.data.map((item) => ({
          userId: item.familyUserId,
          userName: item.familyName,
        }));
        // 清空已选择的访客
        this.form.visitorName = null;
      });
    },
    /** 老人选择改变事件 */
    handleElderChange(value) {
      if (value) {
        this.getFamilyList(value);
      } else {
        this.familyOptions = [];
        this.form.visitorName = null;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        visitorName: null,
        visitorPhone: null,
        visitorIdCard: null,
        elderUserId: null,
        elderName: null,
        visitTime: null,
        leaveTime: null,
        visitReason: null,
        status: "0",
      };
      this.familyOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加来客访记";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getVisitor(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改来客访记";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 设置访客姓名和老人姓名
          const selectedVisitor = this.familyOptions.find(
            (item) => item.userId === this.form.visitorId
          );
          if (selectedVisitor) {
            this.form.visitorName = selectedVisitor.userName;
          }

          const selectedElder = this.elderOptions.find(
            (item) => item.userId === this.form.elderUserId
          );
          if (selectedElder) {
            this.form.elderName = selectedElder.userName;
          }

          if (this.form.id != null) {
            updateVisitor(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVisitor(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除来客访记编号为"' + ids + '"的数据项？')
        .then(function () {
          return delVisitor(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/visitor/export",
        {
          ...this.queryParams,
        },
        `visitor_${new Date().getTime()}.xlsx`
      );
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.auditForm = {
        id: row.id,
        status: "1",
        auditRemark: null,
      };
      this.auditOpen = true;
    },
    /** 取消审核 */
    cancelAudit() {
      this.auditOpen = false;
      this.auditForm = {
        id: null,
        status: "1",
        auditRemark: null,
      };
      this.resetForm("auditForm");
    },
    /** 提交审核 */
    submitAudit() {
      this.$refs["auditForm"].validate((valid) => {
        if (valid) {
          updateVisitor(this.auditForm).then((response) => {
            this.$modal.msgSuccess("审核成功");
            this.auditOpen = false;
            this.getList();
          });
        }
      });
    },
  },
};
</script>
